package com.spancer.contentcenter.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * author by: mars
 * Date: 2020/8/17 17:04
 * Description: 实现相同集群调用Rule
 */
@Slf4j
public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
    }

    @Override
    public Server choose(Object key) {
        // 获取当前服务所属的集群名称
        String clusterName = nacosDiscoveryProperties.getClusterName();
        // 获取微服务名
        BaseLoadBalancer lb = (BaseLoadBalancer)this.getLoadBalancer();
        String name= lb.getName();
        try {
            // 获取服务发现的相关Api
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
            // 获取指定服务的所有健康的实例 A
            List<Instance> instanceList = namingService.selectInstances(name,true);
            // 过滤出相同集群的所有实例 B
            List<Instance> filterInstanceList = instanceList.stream().filter(x->x.getClusterName().equals(clusterName)).collect(Collectors.toList());
            List<Instance> instancesToBeanChosen = new ArrayList<>();
            if (CollectionUtils.isEmpty(filterInstanceList)) {
                instancesToBeanChosen = instanceList;
                log.warn("发生跨集群调用 name={},clusterName={},instanceList={}",name,clusterName,instanceList);
            } else {
                instancesToBeanChosen = filterInstanceList;
            }
            // 给予负载均衡获取实例
            Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToBeanChosen);
            log.info("选择的实例是  port={},instanceInfo={}",instance.getPort(),instance);
            return new NacosServer(instance);
        } catch (NacosException e) {
            log.error("发生异常",e);
            return null;
        }
    }
}

class ExtendBalancer extends Balancer {

    public static Instance getHostByRandomWeight2(List<Instance> hosts) {
        return getHostByRandomWeight(hosts) ;
    }
}